<?php
/**
 * licenses : MIT
 * creatTime: 2020/5/15
 * author : weblinuxgame
 * filename: UuidService.php
 */

namespace App\Services;

use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;

/**
 * Class UuidService
 * @package App\Services
 */
class UuidService
{
    protected $model;
    protected $key;
    public $maxTryTime = 3;

    /**
     * uuid 服务
     * UuidService constructor.
     * @param Model $model
     * @param string $key
     */
    public function __construct(Model $model, $key = 'uuid')
    {
        $this->model = $model;
        $this->key = $key;
    }

    /**
     * 获取最新uuid
     * @return string
     */
    public function get(): string
    {
        $uuid = '';
        while ($this->maxTryTime--) {
            $uuid = Uuid::uuid4()->getHex()->toString();
            if ($this->verify($uuid)) {
                return $uuid;
            }
        }
        return $uuid . time();
    }

    /**
     * 验证是否通过
     * @param string $uuid
     * @return bool
     */
    public function verify(string $uuid): bool
    {
        return !$this->model->newQuery()->where($this->key, $uuid)->exists();
    }
}
